// --- Copyright (c) 2006-2008 Stefan Kyntchev ---
// This software is written and copyrighted by Stefan Kyntchev 
// and BeyondPod Team members. All rights are reserved.
// Author contact: support@beyondpod.mobi
// ------------------------------------------------------------------------
// This file is part of BeyondPod RSS Feed Reader and Podcast manager
// (www.codeplex.com/BeyondPod) 
// BeyondPod is free software: you can redistribute it and/or modify 
// it under the terms of the GNU General Public License as published by 
// the Free Software Foundation, either version 3 of the License, or 
// (at your option) any later version. 
//  
// BeyondPod is distributed in the hope that it will be useful, 
// but WITHOUT ANY WARRANTY; without even the implied warranty of 
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
// GNU General Public License for more details. 
//  
// You should have received a copy of the GNU General Public License
// along with BeyondPod. If not, see <http://www.gnu.org/licenses/>
// ------------------------------------------------------------------------
// COPYRIGHT NOTICE: This copyright notice may NOT be removed, obscured or modified 
// without written consent from the author.
// --- End copyright notice --- 


using System;
using System.Drawing;
using System.Windows.Forms;
using svs.Mobile.BeyondMedia.FeedCore;
using svs.Mobile.BeyondMedia.Objects;
using svs.Mobile.BeyondMedia.UiCore.GDI;

namespace svs.Mobile.BeyondMedia.Controls
{
	public class WebBrowserView : WebBrowser, IView
	{
		private static readonly Uri m_BlankDocument = new Uri("about:blank");
		private string m_Title = string.Empty;

		public event EventHandler BackClick;
		public event Helpers.NavigationEvent Navigation;

		#region Constructors

		public WebBrowserView()
		{
			BrowserCtrl.Navigating += OnNavigating;
		}
		#endregion

		#region Public Properties

		
		/// <summary>
		/// True if the browser control is currently showing a URL that is not one of our default Urls
		/// </summary>
		public bool IsShowingWebPage
		{
			get
			{
				if (BrowserCtrl.Url == null || BrowserCtrl.Url.AbsolutePath.Length == 0)
					return false;

				if (BrowserCtrl.Url.Equals(m_BlankDocument))
					return false;

				return true;
			}
		}

		/// <summary>
		/// True if the browser is currently loading content
		/// </summary>
		public bool IsBrowserBusy
		{
			get { return BrowserCtrl.IsBusy; }
		}

		/// <summary>
		/// Gets the title.
		/// </summary>
		/// <value>The title.</value>
		public string Title
		{
			get
			{
				return string.IsNullOrEmpty(m_Title)? "Loading..." : m_Title;
			}
		}

		/// <summary>
		/// Gets the view menu.
		/// </summary>
		/// <value>The view menu.</value>
		public MainMenu ViewMenu
		{
			get { return MenuManager.GetMenu(Helpers.ViewNames.WebBrowser); }
		}

		#endregion

		#region Public Methods
		public void OnBeforeActivate()
		{
		}

		/// <summary>
		/// Gets a screenshot of the view for transitions
		/// </summary>
		/// <returns></returns>
		public Bitmap CreateScreenShot()
		{
			return Gdi.CreateControlSnapshot(this);
		}

		public void OnAfterDeactivate()
		{
			if(BrowserCtrl.Url != null && !BrowserCtrl.Url.Equals(m_BlankDocument))
				SetExternalURL(m_BlankDocument,string.Empty);
		}

		public void OnAfterActivate()
		{
			BrowserCtrl.Focus();
		}

		public void SetExternalURL(Uri aUri, string title)
		{
			if (InvokeRequired)
			{
				SetExternalUrlDelegate cbDel = SetExternalURL;
				Invoke(cbDel, aUri, title);
				return;
			}

			SetURLInternal(aUri);

			m_Title = title;

			if(!string.IsNullOrEmpty(title))
				ViewManager.RefreshTitle();	

			if (BrowserCtrl.Visible)
				BrowserCtrl.Focus();
		}

		public void NavigateBack()
		{
				if(BrowserCtrl.CanGoBack)
					BrowserCtrl.GoBack();
				else 
					CommandManager.CmdGoToView(Helpers.ViewNames.FeedContent);
		}

		public void BrowserStop()
		{
			BrowserCtrl.Stop();
		}

		public void BrowserRefresh()
		{
				BrowserCtrl.Refresh();
		}

		#endregion

		#region Private Methods

		private WebBrowser BrowserCtrl
		{
			get { return this; }
		}

		protected override void OnKeyDown(KeyEventArgs e)
		{
			switch (e.KeyCode)
			{
					//Left Right
				case Keys.Left:
					OnNavigation(Helpers.NavigationDirection.Back);
					e.Handled = true;
					break;

					//Left Right
				case Keys.Right:
					OnNavigation(Helpers.NavigationDirection.Forward);
					e.Handled = true;
					break;
			}

			if (!e.Handled)
			{
				base.OnKeyDown(e);

				if (!e.Handled)
					e.Handled = ShortcutKeyManager.HandleKey(e.KeyCode);
			}
		}

		protected override void OnKeyPress(KeyPressEventArgs e)
		{
			if (e.KeyChar == (Char) Keys.Escape)
			{
				e.Handled = true;
				if (BackClick != null)
					BackClick(this, null);
			}
		}

		private void OnNavigation(Helpers.NavigationDirection i_direction)
		{
			if (Navigation != null)
				Navigation(this, i_direction);
		}

		private void OnNavigating(object sender, WebBrowserNavigatingEventArgs e)
		{
			//If navigating to the blank page
			if(ViewManager.CurrentViewName == Helpers.ViewNames.WebBrowser && e.Url.Equals(m_BlankDocument))
			{
				CommandManager.CmdGoToView(Helpers.ViewNames.FeedContent);
			}
		}

		private void SetURLInternal(Uri url)
		{
			try
			{
				BrowserCtrl.Url = url;
			}
			catch
			{
				CoreHelper.WriteLogEntry(
					"Failed to set the URL to the Browser Control. Possible .htm extension handler in the registry is invalid!");
			}
		}

		#endregion

		#region Nested type: SetExternalUrlDelegate

		private delegate void SetExternalUrlDelegate(Uri i_uri, string title);

		#endregion

	}
}